package com.bsbm.common.dao.impl;

import com.bsbm.common.dao.UserDao;
import com.bsbm.common.domain.User;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * Created by SABIR IQBAL on 3/26/14.
 */
public class UserDaoImpl extends HibernateDaoSupport implements UserDao{
    @Override
    public void addUser(User user) {
        getHibernateTemplate().save(user);
    }

    @Override
    public void editUser(User user) {
        getHibernateTemplate().update(user);
    }

    @Override
    public void deleteUser(int userId) {
        getHibernateTemplate().delete(findUser(userId));
    }

    @Override
    public User findUser(int userId) {
       return (User) getHibernateTemplate().load(User.class, userId);
        //return (User) getHibernateTemplate().get(User.class, userId);
    }

    @Override
    public User findByUserName(String userName) {
        List<User> users = getHibernateTemplate().findByCriteria(
                DetachedCriteria.forClass(User.class).add(Restrictions.eq("userName", userName)));
        if(CollectionUtils.isEmpty(users)) {
            return null;
        }
        return users.get(0);
    }

    @Override
    public List<User> findAllUser() {
        return getHibernateTemplate().find("from " + User.class.getName());
    }
}
